<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>积分管理</el-breadcrumb-item>
      <el-breadcrumb-item>积分兑换</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入兑换物品名称（模糊搜索）"
            v-model="queryInfo.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getData()"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addDialogVisible = true"
            >添加兑换</el-button
          ></el-col
        >
      </el-row>

      <el-table :data="exchangeList" border style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="id" label="id" width="100px"> </el-table-column>
        <el-table-column prop="coupon_id" label="优惠券id" width="100px">
        </el-table-column>
        <el-table-column prop="coupon.name" label="优惠券名称" width="200px">
        </el-table-column>
        <el-table-column prop="coupon.discount" label="优惠值" width="100px">
        </el-table-column>
        <el-table-column
          prop="coupon.limit_price"
          label="最低消费"
          width="100px"
        >
        </el-table-column>
        <el-table-column
          prop="coupon.expire_time"
          label="有效期（天）"
          width="100px"
        >
        </el-table-column>
        <el-table-column prop="score" label="兑换积分"> </el-table-column>
        <el-table-column prop="count" label="剩余数量"> </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 详细信息 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="详细信息"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-postcard"
                circle
                @click="showInfoDialog(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 显示详细数据 -->
    <el-dialog
      title="兑换信息详情"
      :visible.sync="infoDialogVisible"
      width="80%"
    >
      <!-- 内容主体区 -->
      <el-descriptions title="兑换信息" border :column="3">
        <el-descriptions-item label="id">{{
          currExchange.id
        }}</el-descriptions-item>
        <el-descriptions-item label="兑换积分">{{
          currExchange.score
        }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{
          currExchange.count
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券id">{{
          currExchange.coupon.id
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券名称">{{
          currExchange.coupon.name
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券类型">{{
          currExchange.coupon.coupon_type.name
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券描述">{{
          currExchange.coupon.details
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券折扣值">{{
          currExchange.coupon.discount
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券最低消费（元）">{{
          currExchange.coupon.limit_price
        }}</el-descriptions-item>
        <el-descriptions-item
          label="优惠券绑定商品名称"
          v-if="currExchange.coupon.goods_of_coupon.goods_id != null"
          >{{
            currExchange.coupon.goods ? currExchange.coupon.goods.name : ''
          }}</el-descriptions-item
        >
        <el-descriptions-item label="优惠券有效期（天）">{{
          currExchange.coupon.expire_time
        }}</el-descriptions-item>
        <el-descriptions-item
          label="优惠券绑定商品id"
          v-if="currExchange.coupon.goods_of_coupon.goods_id != null"
          >{{
            currExchange.coupon.goods_of_coupon.goods_id
          }}</el-descriptions-item
        >
      </el-descriptions>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="infoDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 添加兑换物品 -->
    <el-dialog
      @close="addDialogClosed"
      title="添加兑换"
      :visible.sync="addDialogVisible"
      width="60%"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="优惠券" prop="coupon_id">
          <el-select
            v-model="addForm.coupon_id"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
          >
            <el-option
              v-for="item in selectCouponList"
              :key="item.id"
              :label="
                item.name +
                '-优惠-' +
                item.discount +
                '-最低消费-' +
                item.limit_price
              "
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="兑换积分" prop="score">
          <el-input v-model="addForm.score"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input v-model="addForm.count"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addExchange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      currExchange: {
        id: '',
        score: '',
        count: '',
        coupon: {
          coupon_type: {},
          goods_of_coupon: {},
          goods: {
            name: ''
          }
        }
      },
      exchangeList: [],
      addForm: {
        coupon_id: '',
        score: '',
        count: ''
      },
      infoDialogVisible: false,
      selectCouponList: [],
      addFormRules: {
        score: [
          {
            required: true,
            message: '请输入兑换积分',
            trigger: 'blur'
          }
        ],
        count: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }
        ]
      },
      addDialogVisible: false
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const { data: res } = await this.$http.get('/getExchangeCouponList', {
        params: this.queryInfo
      })
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }
      this.exchangeList = res.data.data
      // console.log(this.exchangeList)
      this.total = res.data.totalNum
    },
    async showInfoDialog(exchange) {
      const goodsId = exchange.coupon.goods_of_coupon.goods_id
      if (goodsId != null) {
        // 根据goodsId获取goods
        const { data: res } = await this.$http.get(
          '/getSingleMinGoods/' + goodsId
        )
        if (res.status !== 200) {
          return this.$message.error(res.message)
        }
        exchange.coupon.goods = res.data
      }
      this.currExchange = exchange
      this.infoDialogVisible = true
    },
    addExchange() {
      if (
        this.addForm.coupon_id === '' ||
        this.addForm.coupon_id.length === 0
      ) {
        return this.$message.info('请选择优惠券')
      }

      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.addForm)

        const { data: res } = await this.$http.post('/saveExchangeCoupon', {
          coupon_id: parseInt(this.addForm.coupon_id),
          score: parseInt(this.addForm.score),
          count: parseInt(this.addForm.count)
        })

        if (res.status !== 200) {
          return this.$message.error(res.message)
        }
        this.$message.success('添加兑现信息成功')

        this.addDialogVisible = false
        // 重新获取用户列表数据以更新
        this.getData()
      })
    },
    addDialogClosed() {
      this.addForm = {
        coupon_id: '',
        score: '',
        count: ''
      }
    },
    async remoteMethod(e) {
      const { data: res } = await this.$http.get('/getCouponNameList', {
        params: {
          query: e
        }
      })
      this.selectCouponList = res.data.data
      // console.log(this.selectCouponList)
    },
    async removeById(id) {
      console.log(id)

      // 弹框询问删除
      const confirmRes = await this.$confirm('是否删除该兑换信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      // 如果用户确认删除，返回的是文本confirm
      // 如果用户取消删除，返回的是cancel
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // this.editUserDeleted(id, true)
      const { data: res } = await this.$http.post('/deleteExchangeCoupon/' + id)
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }
      // 更新数据
      this.getData()
      this.$message.success(res.message)
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getData()
    }
  }
}
</script>

<style lang="less" scoped></style>
